package com.centsuse.my_redis.controller;

import com.centsuse.my_redis.dao.CallerToken;
import com.centsuse.my_redis.es.entity.Book;
import com.centsuse.my_redis.es.entity.BookList;
import com.centsuse.my_redis.service.CallerTokenService;
import com.centsuse.my_redis.service.IBookEsService;
import com.centsuse.my_redis.service.impl.BookEsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 业务方Token管理接口
 * @author bobo
 */
@RestController
@RequestMapping("/api/bookes")
public class BookEsController {

    @Autowired
    private IBookEsService bookEsService;

    /**
     * 根据caller标识获取Token信息
     */
    @GetMapping("/{id}")
    public ResponseEntity<Book> getBook(@PathVariable String id) {
        Book book = bookEsService.getBook(id);
        return book != null ?
                ResponseEntity.ok(book) :
                ResponseEntity.notFound().build();
    }

    @GetMapping("/getAll")
    public ResponseEntity<BookList> getAllBook() {
        List<Book> book = bookEsService.getAllBooks();
        BookList bookList = new BookList();
        bookList.setBookList(book);
        return book != null ?
                ResponseEntity.ok(bookList) :
                ResponseEntity.notFound().build();
    }

    /**
     * 创建新的业务方Token
     */
    @PostMapping
    public ResponseEntity<Book> createBook(@RequestBody Book book) {
        Book result = bookEsService.saveBook(book);
        return result != null ?
                ResponseEntity.ok(result) :
                ResponseEntity.badRequest().build();
    }

    @PostMapping("/init")
    public String initIndex() {
        bookEsService.createIndexIfNotExists();
        return "索引初始化成功";
    }
}